import { COLORS, USAGE_THRESHOLD } from '../constants'
import logger from './logger'

/**
 * 根据资源使用率获取颜色
 */
export function getUsageColor(value: number): string {
  if (value >= USAGE_THRESHOLD.CRITICAL) return COLORS.DANGER
  if (value >= USAGE_THRESHOLD.WARNING) return COLORS.WARNING
  return COLORS.SUCCESS
}

/**
 * 根据状态获取CSS类名
 */
export function getStatusClass(status: string): string {
  const statusMap: Record<string, string> = {
    online: 'online',
    offline: 'offline',
    warning: 'warning',
    normal: 'online',
    error: 'offline'
  }
  return statusMap[status] || 'offline'
}

/**
 * 格式化数字 - 添加千分位分隔符
 */
export function formatNumber(num: number | undefined): string {
  if (num === undefined || num === null) return '0'
  return num.toLocaleString()
}

/**
 * 安全地从localStorage获取数据
 */
export function getStorageItem<T = string>(key: string, defaultValue?: T): T | null {
  try {
    const item = localStorage.getItem(key)
    if (!item) return defaultValue ?? null
    
    // 尝试解析JSON
    try {
      return JSON.parse(item) as T
    } catch {
      return item as unknown as T
    }
  } catch (error) {
    console.error(`Error reading from localStorage: ${key}`, error)
    return defaultValue ?? null
  }
}

/**
 * 安全地设置localStorage数据
 */
export function setStorageItem(key: string, value: any): boolean {
  try {
    const stringValue = typeof value === 'string' ? value : JSON.stringify(value)
    localStorage.setItem(key, stringValue)
    return true
  } catch (error) {
    console.error(`Error writing to localStorage: ${key}`, error)
    return false
  }
}

/**
 * 安全地删除localStorage数据
 */
export function removeStorageItem(key: string): boolean {
  try {
    localStorage.removeItem(key)
    return true
  } catch (error) {
    console.error(`Error removing from localStorage: ${key}`, error)
    return false
  }
}

/**
 * 清空所有认证相关的storage
 */
export function clearAuthStorage(): void {
  removeStorageItem('authToken')
  removeStorageItem('username')
  removeStorageItem('userInfo')
}

/**
 * 延迟执行
 */
export function sleep(ms: number): Promise<void> {
  return new Promise(resolve => setTimeout(resolve, ms))
}

/**
 * 判断是否为空值
 */
export function isEmpty(value: any): boolean {
  if (value === null || value === undefined) return true
  if (typeof value === 'string') return value.trim() === ''
  if (Array.isArray(value)) return value.length === 0
  if (typeof value === 'object') return Object.keys(value).length === 0
  return false
}

// 导出日志工具
export { logger }